import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:ota_update_fork/ota_update_fork.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/manager/xindong_permission_ctr.dart';
import 'package:xindong/plugins/xindong_to_native_plugin.dart';
import 'package:xindong/widgets/common/xindong_button.dart';
import 'package:url_launcher/url_launcher.dart';

class XinDongVersionActionView extends StatefulWidget {
  final String url;
  final String version;
  final bool force;

  const XinDongVersionActionView({Key? key, required this.url, required this.version, required this.force})
      : super(key: key);

  @override
  State<XinDongVersionActionView> createState() => _XinDongVersionActionViewState();
}

class _XinDongVersionActionViewState extends State<XinDongVersionActionView> {
  OtaEvent? currentEvent;
  int isShow = 0;
  bool isBackstage = false;

  Future<void> tryOtaUpdate() async {
    try {
      OtaUpdate()
          .execute(
        widget.url,
        destinationFilename: 'xindong.apk',
      )
          .listen(
        (OtaEvent event) {
          currentEvent = event;
          if (currentEvent!.value == "100") {
            isShow = 0;
          }
          if (!isBackstage) {
            setState(() {});
          }
        },
      );
    } catch (e) {
      launchUrl(Uri.parse(widget.url), mode: LaunchMode.externalApplication);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Platform.isIOS
            ? const SizedBox()
            : Container(
                height: 40,
                width: double.infinity,
                margin: const EdgeInsets.only(left: 24, right: 24, top: 20),
                child: XinDongCommonBorderButton(
                  "浏览器下载升级",
                  onTap: () {
                    launchUrl(Uri.parse(widget.url), mode: LaunchMode.externalApplication);
                  },
                ),
              ),

        isShow == 0
            ? Container(
                height: 40,
                width: double.infinity,
                margin: EdgeInsets.only(left: 24, right: 24, top: Platform.isIOS ? 30 : 10),
                child: XinDongCommonBorderButton(
                  "立即升级",
                  onTap: () async {
                    if (Platform.isIOS) {
                      XinDongToNativePlugin.instance.showApplicationStore(url: widget.url);
                    } else {
                      bool storage = await XinDongPermissionCtr.checkPermission(XinDongAppPermission.storage);
                      if (storage) {
                        tryOtaUpdate();
                        setState(() {
                          isShow = 1;
                        });
                      } else {
                        launchUrl(Uri.parse(widget.url), mode: LaunchMode.externalApplication);
                      }
                    }
                  },
                ),
              )
            : isShow == 1
                ? Padding(
                    padding: const EdgeInsets.only(left: 24, right: 24, top: 30),
                    child: Container(
                      clipBehavior: Clip.antiAlias,
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(4)),
                      child: LinearProgressIndicator(
                        value: value() / 100,
                        color: DZColors.mainColor,
                        backgroundColor: DZColors.mainLightColor,
                      ),
                    ),
                  )
                : const Padding(
                    padding: EdgeInsets.only(left: 24, right: 24, top: 30),
                    child: Text("没有获取到权限，请浏览器下载"),
                  ),

        // 取消
        GestureDetector(
          onTap: widget.force
              ? null
              : () {
                  isBackstage = true;
                  SmartDialog.dismiss();
                },
          behavior: HitTestBehavior.opaque,
          child: Container(
            height: 48,
            padding: const EdgeInsets.only(bottom: 8),
            alignment: Alignment.center,
            child: widget.force == false
                ? Text(
                    isShow == 0
                        ? "暂不升级"
                        : isShow == 1
                            ? "后台下载"
                            : "请浏览器下载",
                    style: const TextStyle(fontSize: 15, color: DZColors.placeholderColor),
                  )
                : const Text(
                    "必须升级才能使用",
                    style: TextStyle(fontSize: 15, color: DZColors.placeholderColor),
                  ),
          ),
        ),
      ],
    );
  }

  int value() {
    try {
      return int.parse(currentEvent?.value ?? "0");
    } catch (e) {
      setState(() {
        isShow = 2;
      });
      return 0;
    }
  }
}
